from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.admin.views.decorators import staff_member_required    

from s_te.utils import delete_slug
from xfn.models import XFN
from forms import XFNForm

@staff_member_required
def main(request, template_name="xfn/admin/main.html"):
    """
    The main page of the admin, listing all profiles
    """
    profiles = XFN.objects.all()
    return render_to_response(template_name, {'profiles':profiles, 'nav_page': 'xfn_admin_main'},
                              context_instance=RequestContext(request))
    
@staff_member_required
def create(request, template_name="xfn/admin/create.html"):
    """
    Create a new profile
    """
    if request.POST:
        form = XFNForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="XFN profile created.")
            return HttpResponseRedirect(reverse('xfn_admin_main'))
    else:
        form = XFNForm()
    return render_to_response(template_name, {'form':form},
                              context_instance=RequestContext(request))
    
@staff_member_required
def edit(request, slug, template_name="xfn/admin/edit.html"):
    """
    Edit an existing profile
    """
    profile = get_object_or_404(XFN, slug=slug)
    if request.POST:
        form = XFNForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            request.user.message_set.create(message="XFN profile saved.")
            return HttpResponseRedirect(reverse('xfn_admin_main'))
    else:
        form = XFNForm(instance=profile)
    return render_to_response(template_name, {'profile':profile, 'form':form},
                              context_instance=RequestContext(request))

@staff_member_required
def delete(request):
    """
    Delete an existing profile
    """
    delete_slug(XFN, request)
    request.user.message_set.create(message="XFN profile deleted.")
    return HttpResponseRedirect(reverse('xfn_admin_main'))
